package org.ysu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.minio.errors.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.ysu.entity.Clue;
import org.ysu.entity.Interview;
import org.ysu.entity.Poor;
import org.ysu.mapper.InterviewMapper;
import org.ysu.service.ClueService;
import org.ysu.service.InterviewService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.ysu.service.UploadFileService;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.sql.Date;

/**
 * <p>
 * 走访记录表 服务实现类
 * </p>
 *
 * @author LiuJunDa
 * @since 2024-08-16
 */
@Service
public class InterviewServiceImpl extends ServiceImpl<InterviewMapper, Interview> implements InterviewService {

    @Resource
    UploadFileService uploadFileService;
    @Resource
    InterviewMapper interviewMapper;
    @Resource
    ClueService clueService;

    @Override
    @Transactional
    public Boolean add(Long vcId, Long fId, LocalDate time, String riskType, String riskRemark, BigDecimal income, BigDecimal liability, String suggestion, String detail, MultipartFile photo) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        Clue clue = new Clue();
        clue.setFId(fId);
        clue.setValid(false);
        clueService.update(clue, new QueryWrapper<Clue>().eq("f_id", fId));

        return this.save(new Interview(
                vcId,
                fId,
                time,
                riskType,
                riskRemark,
                income,
                liability,
                suggestion,
                detail,
                uploadFileService.upload("interview",photo)
        ));
    }

    @Override
    public List<Interview> list(Long fId) {
        QueryWrapper<Interview> wrapper = new QueryWrapper<>();
        wrapper.eq("f_id",fId);
        return this.list(wrapper);
    }

    @Override
    public Boolean update(Long id, Long fId, LocalDate time, String riskType, String riskRemark, BigDecimal income, BigDecimal liability, String suggestion, String detail, MultipartFile photo) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        Interview interview = new Interview(
                id,
                fId,
                time,
                riskType,
                riskRemark,
                income,
                liability,
                suggestion,
                detail
        );
        if (photo != null) {
            interview.setPhoto(uploadFileService.upload("interview",photo));
        }
        return this.updateById(interview);
    }
    @Override
    public BigDecimal getAvgIncomeByRegionId(Long regionId) {
        if(interviewMapper.avgIncomeByRegionId(regionId)!=null){
            return interviewMapper.avgIncomeByRegionId(regionId);
        }else {
            return BigDecimal.valueOf(0);
        }
    }

    @Override
    public List<Integer> getDailyInterviewCounts(LocalDate startDate, LocalDate endDate, Long rId) {
        List<Map<String, Object>> resultList = interviewMapper.countInterviewsByDateRangeAndRId(startDate, endDate, rId);

        // 初始化一个按日期排序的Map，保证每天都有一个记录
        Map<LocalDate, Integer> dailyCounts = new LinkedHashMap<>();
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            dailyCounts.put(currentDate, 0); // 初始化每一天的数据条数为0
            currentDate = currentDate.plusDays(1);
        }

        // 统计查询结果
        for (Map<String, Object> result : resultList) {
            Date sqlDate = (Date) result.get("interview_date");
            Integer count = ((Number) result.get("interview_count")).intValue();
            LocalDate date = sqlDate.toLocalDate(); // 转换为 LocalDate
            dailyCounts.put(date, count);
        }

        // 将结果按顺序放入List
        List<Integer> counts = new ArrayList<>();
        currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            counts.add(dailyCounts.get(currentDate));
            currentDate = currentDate.plusDays(1);
        }

        return counts;
    }
    @Override
    public List<List<Object>> getAdminInterviewSummaries(Long rId, LocalDate startDate, LocalDate endDate) {
        // 执行查询
        List<Map<String, Object>> resultList = interviewMapper.getAdminInterviewSummary(rId, startDate, endDate);

        // 转换结果
        List<List<Object>> summaries = new ArrayList<>();
        for (Map<String, Object> result : resultList) {
            List<Object> entry = new ArrayList<>();
            String name = (String) result.get("name");
            Integer interviewCount = ((Number) result.get("interview_count")).intValue();
            entry.add(name);
            entry.add(interviewCount);
            summaries.add(entry);
        }

        // 返回结果
        return summaries;
    }
}
